import ReactDOM from 'react-dom/client';
import { StrictMode, useEffect } from 'react';
import { RouterProvider } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Toaster } from 'react-hot-toast';
import router from './pages/router';
import meStore from './store/me';
import meApis from './apis/me';
import './index.css';

const queryClient = new QueryClient();

function Root() {
  // TODO: 改用 useQuery
  useEffect(() => {
    meApis
      .getMe()
      .then((res) => {
        console.log('get me success', res);
        meStore.setState(() => ({ state: 'authenticated', me: res }));
      })
      .catch((err) => {
        console.warn('get me failed', err);
        meStore.setState(() => ({ state: 'unauthenticated' }));
      });
  }, []);
  return (
    <QueryClientProvider client={queryClient}>
      <RouterProvider router={router} />
    </QueryClientProvider>
  );
}

const rootElement = document.getElementById('root')!;
if (!rootElement.innerHTML) {
  const root = ReactDOM.createRoot(rootElement);
  root.render(
    <StrictMode>
      <Root />
      <Toaster />
    </StrictMode>
  );
}
